<?php

class DkpAdjustments extends Zend_Db_Table_Abstract 
{
	
	protected $_rowClass = 'DkpAdjustmentRow';
	protected $_name = 'dkp_adjustments';
	protected $_dependentTables = array('DkpAdjustmentsCharacters','RaidRosterChanges');
	
	protected $_referenceMap = array(
		'DkpEvents'	=> 	array(
						'columns' 		=> array('dkp_event_id'),
						'refTableClass' => 'DkpEvents',
						'refColumns' 	=> array('id')
						),
		'DkpPools'	=> 	array(
						'columns' 		=> array('dkp_pool_id'),
						'refTableClass' => 'DkpPools',
						'refColumns' 	=> array('id')
						)
	);
	
	
	public function createAdjustment($eventId, $time, $affectedCharacters,$dkpPoolId, $earned=null, $spent=null, $note=null)
	{
		// Characters for this adjustment
		$characters = array();
		
		// Get the event type and make sure its valid
		$eventTable = new DkpEvents();
		$event = $eventTable->fetchRow($eventTable->select()->where("id = ?", $eventId));
		if (!$event) {
			throw new Exception("Invalid event id given: " + $eventId + " see dkp_events for ids.");
		}
		
		// Get default earned and spent values if non are given
		if (!$earned) $earned = $event->default_earned;
		if (!$spent) $spent = $event->default_spent;
		
		// Affected characters can be either:
	 	// 	* a rowset of characters 
	 	//  * a character row
	 	//  * a array of character ids
	 	//  * a single character id
		if ($affectedCharacters instanceof Zend_Db_Table_Rowset_Abstract) {
			
			foreach($affectedCharacters as $character) {
				$characters[] = $character->id;
			}
			
		} else if ($affectedCharacters instanceof Zend_Db_Table_Row_Abstract) {
			
			$characters[] = $affectedCharacters->id;
			
		} else if (is_array($affectedCharacters)) {
			
			$characters = $affectedCharacters;
			
		} else if (is_numeric($affectedCharacters)) {
			
			$characters[] = $affectedCharacters;
			
		}
		
		// Make sure that characters contains elements
		if (!is_array($characters) || empty($characters)) {
			throw new Exception("Can't add a adjustment with a empty character set.");
		}
		
		//throw new Exception("Creating: " . $event->name . "\n Spent: " . $spent . " Earned: " . $earned . "\n Characters: " . implode(",",$characters));
		
		// Formulate the insert data
		$data = array(
			"time" 			=> $time, 
			"dkp_earned" 	=> $earned, 
			"dkp_spent" 	=> $spent,
			"dkp_event_id" 	=> $event->id,
			"dkp_pool_id"	=> $dkpPoolId,
			"note" 			=> $note
		);
			
		$adjustmentId = $this->insert($data);
		
		if (!$adjustmentId) {
			return null;
		}
		
		$adjustment = $this->find($adjustmentId)->current();
		$adjustment->setCharacters($characters);
		
		return $adjustment;
	}
}
?>